#include "key_exti.h"

void KEY_Init()
{
    KEY_GPIO_Init();
    KEY_EXTI_Init();
    KEY_NVIC_Init();
}

//第一步，初始化要连接到EXTI的GPIO
void KEY_GPIO_Init()
{
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB2PeriphClockCmd(KEY_EXTI_GPIO_CLK,ENABLE);

    GPIO_InitStructure.GPIO_Pin = KEY_EXTI_GPIO_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    //GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;//输入情况下可以不用

    GPIO_Init(KEY_EXTI_GPIO_PORT, &GPIO_InitStructure);
}

//初始化EXYI外设
void KEY_EXTI_Init()
{
    EXTI_InitTypeDef EXTI_InitStructure;
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
    //选择输入线，第一个参数是GPIO_PortSourceGPIOx（x=A~G）,第二个参数是GPIO_PinSourcex(x=0~15)
    GPIO_EXTILineConfig(GPIO_PortSourceGPIOA,GPIO_PinSource0);
    EXTI_InitStructure.EXTI_Line=EXTI_Line0;
    EXTI_InitStructure.EXTI_Mode=EXTI_Mode_Interrupt;
    EXTI_InitStructure.EXTI_Trigger=EXTI_Trigger_Falling;
    EXTI_InitStructure.EXTI_LineCmd=ENABLE;

    EXTI_Init(&EXTI_InitStructure);
}

void KEY_NVIC_Init()
{
    //第一步，配置中断优先级分组
    NVIC_InitTypeDef NVIC_InitStructure;

    //分组
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

    NVIC_InitStructure.NVIC_IRQChannel=EXTI0_IRQn;//写入中断源
    //写入主优先级
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1;
    //写入从优先级
    NVIC_InitStructure.NVIC_IRQChannelSubPriority=1;
    //使能
    NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
    //把配置好的结构体写入寄存器内
    NVIC_Init(&NVIC_InitStructure);

}

int flag;
void EXTI0_IRQHandler()
{
    
    if(EXTI_GetITStatus(EXTI_Line0)!=RESET)
    {
        flag=!flag;
        if (flag)
        {
            LED1_Control(0,0,1);
        }
        else
        {
            LED1_Control(0,0,0);
        }
    }
    EXTI_ClearITPendingBit(EXTI_Line0);
}


